let app = getApp();
import { 
  getPersonAuth, 
  realPersonAuth, 
  getOcr, 
  checkPersonAuth, 
  createPreAuth, 
  createContract,
  createHuabei,
  createAntchain
} from "../../api/index";
import { uploadImg } from "../../utils/request";
import { checkName, validateIdCard } from "../../utils/validate";
import { disposeData, backMini } from "../../utils/outData";
import  {baseUrl} from '../../setting'
const esignPlugin = requirePlugin("esign");
Page({
  data: {
    userName: '',
    userIdcard: '',
    card_front: '',
    card_back: '',
    frontCard: [],
    backCard: [],
    orderId: '',
    payType: '',
    contractType: '',  //合同类型  1蚂蚁智能合同  2E签宝合同
    // signNum: '',       //签署方数量   2两方  3三方
    isReady: false,
    isAuth: '',
    orderStatus: '',
    esignFlowId: '',
    esignUserId: '',
    disabled:false
  },
  onLoad(option) {
    my.removeStorage({key: 'hasCreateSign' });
    console.log('option', option)
    const {orderId, payType, esignUserId, flowId, isAuth, status, contractType} = option
    this.setData({
      orderId,
      payType,
      isAuth,
      orderStatus: status,
      esignFlowId: flowId,
      esignUserId,
      contractType,
    })

  },
  onShow(){
    getPersonAuth().then(res =>{
        this.setData({
          userName: res.certName,
          userIdcard: res.certNo,
          card_front: res.cardFront,
          card_back: res.cardBack,
        })
    })
    my.setStorageSync({ key: 'isAuthShow', data: true })
    setTimeout(() => { my.hideLoading()}, 500);
    let hasCreateSign = my.getStorageSync({key: 'hasCreateSign'}).data;
    if (hasCreateSign) {
      const { code } = esignPlugin.getSignStatusInfo();
      // console.log('code：',code)
      if (code == '000') {
        my.showLoading({ content: '跳转中...' });
        setTimeout(() => { my.hideLoading()}, 1500);
        my.reLaunch({
          url: '../paySuccess/paySuccess?orderId=' + this.data.orderId
        })
      }
    }
  },
  onName(e){
    this.setData({ userName: e.detail.value })
  },
  onIdcard(e){
    this.setData({ userIdcard: e.detail.value })
  },
  uploadPhoto(e){
    const that = this;
    let cardId = e.currentTarget.dataset.id
    let list= []
    if(cardId ==1){
      uploadImg(function (url) {
        if (url) {
          list.push(url);
          that.setData({
            frontCard: list,
            card_front: list[0]
          })

          // getOcr({
          //   cardFront: list[0]
          // }).then(res =>{
          //        console.log('实人认证',res);
          //        if (res.data.face.data.name) {

          //         that.setData({
          //           userName: res.data.face.data.name,
          //           userIdcard: res.data.face.data.idNumber
          //         })
          //       }
          // })
        }
      });
    } else {
      uploadImg(function (url) {
        if (url) {
          list.push(url);
          that.setData({
            backCard: list,
            card_back: list[0]
          })
          // console.log(list)
          // getOcr({
          //   card_back: list[0]
          // }).then(res =>{
          // })
        }
      });
    }
  },

  // uploadPhoto(e){
  //   const that = this;
  //   let cardId = e.currentTarget.dataset.id
  //   let list= []
  //   if(cardId ==1){
  //     uploadImg(function (url) {
  //       if (url) {
  //         list.push(url);
  //         that.setData({
  //           frontCard: list,
  //           card_front: list[0]
  //         })
  //       }
  //     });
  //   } else {
  //     uploadImg(function (url) {
  //       if (url) {
  //         list.push(url);
  //         that.setData({
  //           backCard: list,
  //           card_back: list[0]
  //         })
  //       }
  //     });
  //   }
  // },
  // e签宝
  isContract(){
    const that = this
    const { orderId, esignFlowId, esignUserId } = that.data
    //sml prod
    const env = 'prod'
    if( (esignFlowId &&esignFlowId!=0 &&esignFlowId!='null') && esignUserId){
      my.setStorage({key: 'hasCreateSign', data: true });
      my.showLoading({ content: '正在跳转合同...' });
      setTimeout(() => { my.hideLoading() }, 800);
      // my.navigateTo({
      //   url: `plugin://esign/esign?env=${env}&flowId=${esignFlowId}&signerId=${esignUserId}`,
      // })
      createContract(orderId).then(res =>{
        console.log('调起合同', res)
        if(res.flowId){
          const { flowId, signerId } = res
          console.log('走到合同签名');
          // my.navigateTo({
          //   url: `plugin://esign/esign?env=${env}&flowId=${flowId}&signerId=${signerId}`,
          // })
          my.ap.openURL({
            url: `${baseUrl}/2.html?openUrl=${res.contractUrl}&orderid=${orderId}`, // 请将 url 替换为有效的页面地址
            success: (res) => {
              my.redirectTo({
                url: '../myOrder/myOrder?order_status=0'
              });
            },
            fail: (err) => {
              console.log('openURL success', err)
            }
          });
        }
      })
    } else {
      my.showLoading({ content: '正在跳转合同...' });
      createContract(orderId).then(res =>{
         console.log('调起合同', res)
        if(res.flowId){
          my.hideLoading({ page: that });
          my.setStorage({key: 'hasCreateSign', data: true });
          const { flowId, signerId } = res
          console.log('走到合同签名');
          // my.navigateTo({
          //   url: `plugin://esign/esign?env=${env}&flowId=${flowId}&signerId=${signerId}`,
          // })
          my.ap.openURL({
            url: `${baseUrl}/2.html?openUrl=${res.contractUrl}&orderid=${orderId}`, // 请将 url 替换为有效的页面地址
            success: (res) => {
              my.redirectTo({
                url: '../myOrder/myOrder?order_status=0'
              });
            },
            fail: (err) => {
              console.log('openURL success', err)
            }
          });
        }
      })
    }
  },

  // 预授权
  createAuth(){
    const that = this;
    const { orderId, payType } = that.data
    console.log(orderId,payType)
    if(payType == 2){
      createPreAuth(orderId).then(res =>{
        console.log('预授权支付', res)
        if(res.orderStr){
          console.log('支付');
          my.tradePay({
            orderStr: res.orderStr,
            success: (res) => {
              if(res.resultCode == 9000){
                // that.isContract()
          
                that.isContract()
              } else {
                my.showToast({
                  type: 'fail',
                  content: '支付未完成',
                  duration: 1000,
                });
              }
            },
            fail: (res) => {
              my.showToast({
                type: 'fail',
                content: '支付失败，请稍后重试',
                duration: 1000,
              });
            }
          });
        } else {
          that.isContract()
        }
      })
    } else if(payType == 3){
      createHuabei(orderId).then(res =>{
        // console.log('花呗支付', res)
        if(res.trade_no) {
          my.tradePay({
            tradeNO: res.trade_no,
            success: (res) => {
              let data = JSON.parse(JSON.stringify(res))
              // console.log('data',data)
              if (data.resultCode == 9000) {
                that.isContract()
              } else {
                my.showToast({
                  type: 'fail',
                  content: '支付失败，请稍后重试',
                  duration: 1000,
                });
              }
            }
          });
        } else {
          if(res.sign_status == 0){
            that.isContract()
          } else if(res.sign_status == 1){
            my.confirm({
              title: '提示',
              content: '继续签署合同?',
              confirmButtonText: '是,继续',
              cancelButtonText: '否,回首页',
              success: info => {
                if (info.confirm) {
                  my.showLoading({ content: '正在跳转合同...' });
                  setTimeout(() => { my.hideLoading() }, 800);
                  my.setStorage({key: 'hasCreateSign', data: true });
                  my.navigateTo({
                    url: `plugin://esign/esign?env=${'prod'}&flowId=${res.flow_id}&signerId=${res.esign_user_id}`,
                  })
                } else {
                  my.switchTab({ url: '../index/index' })
                }
              },
            });
          } else {
            my.showLoading({ content: '合同已签署完成...' });
            setTimeout(() => { my.hideLoading()}, 1000);
            my.reLaunch({
              url: '../success/success'
            })
          }
        }
      })
    }
  },
  toAuth(){
    const that = this
    const {userName,userIdcard, orderId, card_front, card_back, orderStatus, contractType } = that.data
    if(!userName || !userIdcard){
      my.showToast({
        type: 'none',
        duration: 1500,
        content: '个人信息不能为空'
      });
      return
    } else if(!card_front || !card_back){
      my.showToast({
        type: 'none',
        duration: 1500,
        content: '证件照不能为空'
      });
      return
    }

      //   createContract(orderId).then(res =>{
      //   // console.log('调起合同', res)
      //   if(res.flowId){
      //     my.hideLoading({ page: that });
      //     my.setStorage({key: 'hasCreateSign', data: true });
      //     const { flowId, signerId } = res
      //     my.navigateTo({
      //       url: `plugin://esign/esign?env=${env}&flowId=${flowId}&signerId=${signerId}`,
      //     })
      //   }
      // })
    if ( userName && !checkName(userName)) {
      return;
    }
    if ( userIdcard && !validateIdCard(userIdcard)) {
      return;
    }
    realPersonAuth({
      orderId,
      certName: userName,
      certNo: userIdcard,
      cardFront: card_front,
      cardBack: card_back
    }).then(res =>{
      console.log('实人认证',res,orderStatus,'544')
      if(orderStatus == 3 || orderStatus == 9 || orderStatus == 10){
        if(contractType ==1){
          my.navigateTo({
            url: '../chainContract/chainContract?orderId=' +orderId
          })
        } else if(contractType ==2){
          that.isContract()
        }
      } else {
        if(res.certify_id){
          console.log('走到付款');
          my.startAPVerify({
            url: res.certify_url,
            certifyId: res.certify_id,
            success: function (info){
              console.log(info,111);
              checkPersonAuth(res.certify_id).then()
              if(info.resultStatus == 9000){
                if(contractType == 1){
                  my.navigateTo({
                    url: '../chainContract/chainContract?orderId=' +orderId
                  })
                } else {
                  that.createAuth()
                }
              }
            }
          })
        } else {
          if(contractType == 1){
            my.navigateTo({
              url: '../chainContract/chainContract?orderId=' +orderId
            })
          } else {
            that.createAuth()
          }
        }
      }
    }).fail((err)=>{
      console.log(err,'认证失败');
    })
  },
  submitBtn(){
    this.toAuth()
  }
});
